package common.server.event;

import common.server.utils.NamedThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

/**
 * 事件总线
 * @author Administrator
 * @version [版本号, 2017/11/29 0029]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class EventBus {


    /**
     * 核心线程数
     */
    private static final int  CORE_POOL_SIZE=Runtime.getRuntime().availableProcessors()*2;

    /**
     * 最大线程数
     */
    private static final int  MAX_NUM_POOL_SIZE =Runtime.getRuntime().availableProcessors()*10;

    /**
     * 闲置线程存活时间
     */
    private static final int  KEEP_ALIVE_TIME =30000;


    /**
     * 线程队列
     */
    private static final int  QUEUE_SEIZ =10000;


    public static final EventBus I = new EventBus();

    /**
     * 日志
     */
    protected static final Logger logger = LoggerFactory.getLogger(EventBus.class);

    /**
     * google EventBus
     */
    private com.google.common.eventbus.EventBus eventBus;

    /**
     * 创建事件总线
     */
    private EventBus(){
        try {
            this.eventBus = new com.google.common.eventbus.AsyncEventBus(new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_NUM_POOL_SIZE,KEEP_ALIVE_TIME,TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(QUEUE_SEIZ), NamedThreadFactory.build("Event",true)),
                    (exception, context) -> logger.error("event bus subscriber ex", exception));
        }catch (Exception e){
            logger.error("new EventBus ex", e);
        }
    }

    /**
     *
     * @param event
     */
    public void post(Event event) {
        this.eventBus.post(event);
    }

    /**
     * 注冊事件
     * @param bean
     */
    public void register(Object bean) {
        this.eventBus.register(bean);
    }

    /**
     * 注销事件
     * @param bean
     */
    public void unregister(Object bean) {
        this.eventBus.unregister(bean);
    }
}
